package com.company.cloud.sdk.core.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ApiUtil {
    private static Pattern linePattern = Pattern.compile("_(\\w)");

    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /** 下划线转驼峰 */
    public static String line2Hump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /** 驼峰转下划线 */
    public static String hump2Line(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 拼接参数字符串
     * @param params
     * @return
     */
    public static String joinParams(Map<String, String> params) {
        StringBuffer content = new StringBuffer();
        for (String key : params.keySet()) {
            String value = params.get(key);
            content.append(key + "=" + value + "&");
        }
        return content.substring(0,content.length()-1);
    }

    /**
     * 对象转Map
     * @param obj
     * @return
     * @throws Exception
     */
    public static Map<String, String> objectToMap(Object obj){
        Map<String, String> map = new HashMap<String,String>();
        try{
            Class<?> clazz = obj.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = hump2Line(field.getName());
                String value = field.get(obj) == null ?"":(String)field.get(obj);
                map.put(fieldName, value);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

}
